<? 

//	**************************************
//	SbSE DB multiple rows update component
//	v1.1.1 / 2011.09.18
//	**************************************

require_once E.'_lib/_db.php';
require_once E.'_lib/_lib.php';

class DB_UPDATE {

	var $tables;	// FROM
	var $where;		// WHERE
	var $replacement;	// replacement

	var $res;

	var $err = array (
		0 => 'success',
		1 => 'empty result',
		255 => 'not initialized'
	);
	
	function DB_UPDATE() {

		$this->tables = '';
		$this->where = '1=1';
		$this->replacement = '';
		
		$this->ai_field = 0;

		$this->db = false;
		

		$this->res = 255;
	}

	function updateRec($rec) {	// store single record with AI (by sequencer $seq) & CLOB processing

		if (defined('USE_ADODB_OCI')) {
			$clob = array();	// get clob fields
			foreach($rec as $k => $v)
				if (is_string($v)) {
					if (strlen($v) > 4000) {
						$clob[$k] = $v;
						$rec[$k] = '';
					} else 
					if ($v == 'NULL')
						$rec[$k] = '';
				}
		}
		
		$this->db->AutoExecute($this->tables, $rec, 'UPDATE', $this->where);
		
		if (defined('USE_ADODB_OCI'))
			foreach($clob as $k => $v)
				$this->db->UpdateClob($this->tables, $k, $v, $this->where);
	}

	function init( $tables, $replacement = '', $where = '', $ai_field = 'id', $db = false ) {
	
		if ($tables)
			$this->tables = str_replace(';', '', $tables);
		else
			return 0;	// error 255 - not initialized.
			
		if (defined('USE_ADODB'))
			if (!$db && isset($GLOBALS['db']))
				$db = $GLOBALS['db'];
			
		$this->db = $db;
		$this->ai_field = $ai_field;

		if ($replacement)
			$this->replacement = $replacement;
		else 
			return 0;

		if ($where)
			$this->where = str_replace(';', '', $where);


//		$this->res = $this->fetch();
		$this->res = (defined('DBProto')) ? $this->fetch() : -1;

		return ! (bool) $this->res;
	}


	function fetch() {

		if (defined('USE_ADODB') && $this->db) {
			
			if ( is_array($this->replacement) )
				$this->updateRec($this->replacement);
			else
				$this->db->Execute("UPDATE {$this->tables} SET {$this->replacement} WHERE ({$this->where})");

		} else {
		
			if ( is_array($this->replacement) ) {
				$temp = '';
				foreach ($this->replacement as $k => $v) 
					$temp .= ($v == 'NULL') ? ",$k=NULL" : ",$k='".sql_safe($v)."'";
				$this->replacement = substr($temp, 1);
			}
			
			$q = new SQL("UPDATE {$this->tables} SET {$this->replacement} WHERE ({$this->where})");
			$q->run();
		}
			
		return 0;		// ok
	}
	

	function error() { return $this->err[$this->res]; }

}
